package org.insidesource.flexbugs.dao.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.insidesource.flexbugs.dao.IssueDao;
import org.insidesource.flexbugs.model.Issue;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;

public class IssueDaoJpaImpl extends JpaDaoSupport implements IssueDao
{

	public Issue get(final Long id)
	{
		//method 1:	
		return this.getJpaTemplate().find(Issue.class, id);
		
		//method 2: 
//		return (Issue)this.getJpaTemplate().find("select iss from Issue iss where iss.id=?1", id).get(0);
		
		//method 3: use callback function directly
		/*
		return (Issue)this.getJpaTemplate().execute(new JpaCallback(){
			public Object doInJpa(EntityManager em) throws PersistenceException
			{
				Query query = em.createQuery("from Issue as iss where iss.id=:id");
				query.setParameter("id", id);
				
				return query.getResultList().get(0);
			}
		});
		*/
		
		//method 4:
		/*
		Map<String, Long> params = new HashMap<String, Long>();
		params.put("id", id);
		return (Issue)this.getJpaTemplate().findByNamedParams("from Issue as iss where iss.id=:id", params).get(0);
		*/
	}

	@SuppressWarnings("unchecked")
	public List<Issue> getAll()
	{
		return this.getJpaTemplate().find("from issue");
	}

	public void remove(Long id)
	{
		Issue issue = get(id);
		this.getJpaTemplate().remove(issue);
	}

	public void save(Issue issue)
	{
		this.getJpaTemplate().persist(issue);
	}

}
